<template>
  <div class="splittingImg">
    <div class="pl20 pr20">
      <div ref="tabHeight" class="clear_fixed">
        <head-tab-switch class="fl" navTitle="影像列表" secondTitle="/ 拆分" />
        <!-- 36371  需求 返回按钮位置变化-->

        <!-- <a @click.prevent="toImgList" class="fr mt20 lh20 clr_0a70b0" v-show="!oldAccession2">
          <span class="f14 fr">返回</span>
          <i class="iconfont mr5 fr vam">&#xe68d;</i>
        </a> -->
      </div>
      <!-- 主检查 -->

      <div>
        <div class="clear_fixed">
          <div class="processBox fl">
            <i class="iconfont clr_0a70b0 f38i">&#xe675;</i>
            <!-- <div class="position_absolute clr_fff top10 left28 f14">第一步：</div> -->
          </div>
          <div class="fl ml30">
            <span>检查编号：</span>
            <el-input size="medium" placeholder="请输入待拆分的影像检查编号" style="width:300px;" v-model="stepOneCheckNum"
              @keyup.native.enter="oldQueryFn" clearable>
            </el-input>
            <el-select class="ml15" v-show="this.splitInfoDataCheckList.length > 0" v-model="selectedSplitInfo" placeholder="请选择"
              style="width:120px" clearable @change="mainCheckChanged">
              <el-option v-for="item in splitInfoDataCheckList" :key="item.id" :label="item.name"
                :value="item.id"></el-option>
            </el-select>
            <div class="btnBox">
              <el-button type="primary" plain size="medium" @click="oldQueryFn">查询</el-button>
              <el-button type="success" class="subButton" size="medium" @click="addAccession">新增子检查</el-button>
            </div>

          </div>

          <div class="spiltBtnBox mr15 fr">
            <!-- 36371  需求 拆分 改为 确认 并修改返回按钮位置样式-->
            <el-button class="splitBtn mr15" size="medium" v-show="fromList" @click="toImgList">返回</el-button>

            <el-button class="splitBtn" type="warning" size="medium" :disabled="splitDisabled"
              @click="splitFn">确认</el-button>
          </div>
        </div>
        <div class="patient_info">
          <div class="patient_info_index">
            <div class="f18">
              <span class="mr30">{{ oldInfo.other_patient_name ? oldInfo.other_patient_name : oldInfo.patient_name
              }}</span>
              <span class="mr30">{{ oldInfo.patient_sex === 'M' ? '男' : oldInfo.patient_sex === 'F' ? '女' :
                oldInfo.patient_sex === 'O' ? '未知' : '' }}</span>
              <span>{{ oldInfo.patient_age | ageFormatter }}</span>
            </div>
            <div class="f14 mt10">
              <span class="mr54">检查编号：{{ oldInfo.accession_number }}</span>
              <span class="mr54">患者编号：{{ oldInfo.patient_id }}</span>
              <span class="mr54">检查项目：{{ oldInfo.examination_item_name }}</span>
              <span class="mr54">检查类型：{{ oldInfo.modalities_in_study }}</span>
              <span>检查日期：{{ oldInfo.study_date_time }}</span>
            </div>
            <div class="f14 mt8">检查描述：{{ oldInfo.study_description }}</div>
          </div>

        </div>
          <div class="h250  flex_row">
            <div class="w160 h250 bradius5 mr54 flex_position flex_column" style="border: 1px dashed #999">
              <div class="w56 bbd pb22 mb22">
                <p class="f18">序列数</p>
                <i class="f28">{{ oldSeriesCount }}</i>
              </div>
              <div class="w56">
                <p class="f18">实例数</p>
                <i class="f28">{{ oldImagesCount }}</i>
              </div>
            </div>
            <div class="of img_box box_img_width">
              <!--          <div class="w196 f14">-->
              <!--            <img src="../../assets/images/logo.png" class="w196 h180">-->
              <!--            <p class="mt5 mb5">序列编号：1</p>-->
              <!--            <span>序列描述：这是一个序列描述的详情</span>-->
              <!--          </div>-->
              <div v-for="(item, index) in oldSeriesData.filter(e => !e.isHidden)" :key="index"
                class="w196 f14 position_relative">
                <el-image v-if="item.imgSrc" class="w196 h180" :src="item.imgSrc">
                  <!--              <div slot="placeholder" class="image-slot w100 h100 position_relative" style="text-align: center">-->
                  <!--                <p class="mt20 clr_999">加载中...</p>-->
                  <!--                <i class="el-icon-picture-outline f30 clr_999 position_absolute toCenter"></i>-->
                  <!--              </div>-->
                  <div slot="error" class="image-slot w100 h100 position_relative">
                    <i v-if="item.id" class="imgLoadFail position_absolute toCenter"></i>
                    <i v-else class="noImg position_absolute toCenter"></i>
                  </div>
                </el-image>
                <el-image v-else class="w196 h180" src="noImg">
                  <div slot="error" class="image-slot w100 h100 position_relative">
                    <i class="noImg position_absolute toCenter"></i>
                  </div>
                </el-image>
                <div v-if="oldCheckList.includes(item.id)" class="position_absolute w196 h180 boxs"
                  style="border: 4px solid #1C8BE4;top: 0"></div>
                <p class="mt5 mb5">序列编号：{{ item.series_number }}</p>
                <span>序列描述：{{ item.series_description }}</span>
                <el-checkbox v-model="oldCheckList" :label="item.id" class="position_absolute"
                  style="top:0;right: 0;left: 0;bottom: 0;"><span></span></el-checkbox>

              </div>
            </div>
          </div>
      </div>
      <!-- 子检查 -->
      <div v-for="(newInfo, index) in newInfoList" :key="index">
        <div class="mt10 of clear_fixed">
          <div class="processBox fl">
            <i class="iconfont clr_0a70b0 f38i">&#xe675;</i>
            <!-- <div class="position_absolute clr_fff top10 left28 f14">第二步：</div> -->

          </div>
          <!-- <div class="fl ml10 subCheck">
            <span>子检查{{ index + 1 }}</span>
          
          </div> -->

          <div class="fl ml10">
            <span class="subCheck">子检查{{ index + 1 }} </span>

            <span>检查编号：</span>
            <el-input size="medium" placeholder="请输入将影像拆分到的检查编号" style="width:300px;" v-model="newStepNums[index]"
              @keyup.native.enter="newQueryFn(index)" clearable>
            </el-input>
            <div class="btnBox">
              <el-button type="primary" plain size="medium" @click="newQueryFn(index)">查询</el-button>
            </div>
          </div>


          <div class="stepTwoBtnBox mr20">
            <el-button @click="seriesCopy(index)" type="primary" plain><i
                class="iconfont mr5">&#xe688;</i>序列复制</el-button>
            <el-button @click="seriesCut(index)" type="primary" plain class="ml20i"><i
                class="iconfont mr5">&#xe67a;</i>序列剪切</el-button>
            <!-- 添加 复原 移除按钮 -->
            <el-button  type="primary" plain size="medium" @click="recoverSubcheckFn(index)">恢复</el-button>
            <el-button type="danger" plain size="medium" @click="removeSubcheckFn(index)">移除</el-button>
          </div>
        </div>
        <div v-show="isQuerySecond" class="patient_info" style="height: 80px">
          <div class="f22 fl ml5 mt5">
            <span>{{ index + 1 }}</span>
          </div>
          <div class="patient_info_index">

            <div class="f18">
              <span class="mr30">{{ newInfo.patient_name }}</span>
              <span class="mr30">{{ newInfo.patient_sex }}</span>
              <span>{{ newInfo.patient_age | ageFormatter }}</span>
            </div>
            <div class="f14 mt15">
              <span class="mr54">检查编号：{{ newInfo.accession_number }}</span>
              <span class="mr54">患者编号：{{ newInfo.patient_id }}</span>
              <span class="mr54">检查项目：{{ newInfo.examination_item_name }}</span>
              <span class="mr54">检查类型：{{ newInfo.modalities_in_study }}</span>
              <span>检查日期：{{ newInfo.study_date_time }}</span>
            </div>
          </div>

        </div>
        <div class="h250 flex_row">
          <div class="w160 h250 bradius5 mr54 flex_position flex_column" style="border: 1px dashed #999">
            <div class="w56 bbd pb22 mb22">
              <p class="f18">序列数</p>
              <i class="f28"> {{ allSeriesCount[index] }} </i>
            </div>
            <div class="w56">
              <p class="f18">实例数</p>
              <i class="f28">{{ allImageCount[index] }}</i>
            </div>
          </div>
          <div class="of img_box box_img_width">
            <!--          <div class="w196 f14">-->
            <!--            <img src="../../assets/images/logo.png" class="w196 h180">-->
            <!--            <p class="mt5 mb5">序列编号：1</p>-->
            <!--            <span>序列描述：这是一个序列描述的详情</span>-->
            <!--          </div>-->
            <div v-for="(item, itemIndex) in newSeriesDataList[index]" :key="itemIndex" class="w196 f14 position_relative">
              <el-image v-if="item.imgSrc" class="w196 h180" :src="item.imgSrc" :preview-src-list="[item.imgSrc]">
                <!--              <div slot="placeholder" class="image-slot w100 h100 position_relative" style="text-align: center">-->
                <!--                <p class="mt20 clr_999">加载中...</p>-->
                <!--                <i class="el-icon-picture-outline f30 clr_999 position_absolute toCenter"></i>-->
                <!--              </div>-->
                <div slot="error" class="image-slot w100 h100 position_relative">
                  <i v-if="item.id" class="imgLoadFail position_absolute toCenter"></i>
                  <i v-else class="noImg position_absolute toCenter"></i>
                </div>
              </el-image>
              <el-image v-else class="w196 h180" src="noImg">
                <div slot="error" class="image-slot w100 h100 position_relative">
                  <i class="noImg position_absolute toCenter"></i>
                </div>
              </el-image>
              <div v-if="newCheckList[index].includes(item.id)" class="position_absolute w196 h180 boxs"
                  style="border: 4px solid #1C8BE4;top: 0"></div>
              <p class="mt5 mb5">序列编号：{{ item.series_number }}</p>
              <span>序列描述：{{ item.series_description }}</span>
              <el-checkbox v-model="newCheckList[index]" :label="item.id" class="position_absolute"
                  style="top:0;right: 0;left: 0;bottom: 0;"><span></span></el-checkbox>
            </div>
          </div>
        </div>
      </div>



      <SplitImgVue :splitImageShow="splitImageShow" :splitImageData="newSeriesDataList" :oldImageData="oldSeriesData"
        :splitInfoData="newInfoList" :oldInfoData="oldInfo" @SplitClose="SplitClose" />

    </div>
  </div>
</template>

<script>
import HeadTabSwitch from '@/components/common/HeadTabSwitch' // 头部tab
import SplitImgVue from '@/components/pacs/commonDialog/SplitImg' // 交换
import { mapGetters } from 'vuex'
import store from '@/store/index'

export default {
  name: 'splitting',
  data() {
    // 36371客服需求 页面改造----- 支持多个检查编号拆分
    return {
      splitImageShow: false,
      basePath: '',
      allSeriesCount: [],
      allImageCount: [],
      oldSeriesCount: '',
      oldImagesCount: '',
      newStepNums: [],//stepOneCheckNum  stepTwoCheckNum
      allAccessionNumbers: [],//所有检查编号
      allAccessionNumberModels: [],//所有检查编号模型{num,index}
      newOneOldNums: [],
      newSeriesDataList: [],
      newInfoList: [],
      stepOneCheckNum: '',
      originalMainCheckNum: '',
      stepTwoCheckNum: '',
      oldInfo: { id: '', other_patient_name: '', patient_sex: '', patient_age: '', accession_number: '', modalities_in_study: '', study_date_time: '', study_description: '' },
      oldSeriesData: [],
      newInfo: { patient_id: '', patient_name: '', patient_sex: '', patient_age: '', accession_number: '', modalities_in_study: '', study_date_time: '' },
      newSeriesData: [],
      apiUrl: '',
      oldCheckList: [],
      newCheckList: [],
      isQuerySecond: false,
      loading: false,
      splitDisabled: false,////取消患者编号不同不能拆分限制
      // oldAccession2: '',
      fromList: true,//是从影像列表页面进入
      // splitInfoDataList: [],//是否待拆分
      splitInfoDataCheckList: [],//待选择的检查列表
      selectedSplitInfo:'',
      selected_number_id:'',


    }
  },
  computed: {
    ...mapGetters(['closeLoading', 'group']),

    // oldSeriesCount() {
    //   //兼容后期恢复问题
    //   debugger
    //   return this.oldSeriesData.filter(e => !e.isHidden).length
    // },
    // oldImagesCount() {
    //   //兼容
    //   return this.oldSeriesData.filter(e => !e.isHidden).reduce((totalVal, currentVal) => {
    //     return totalVal + currentVal.images_count
    //   }, 0)
    // },
    // newwSeriesCount() {
    //   return 1
    //   // this.newSeriesData.length
    // },
    // newImagesCount() {
    //   return this.newSeriesData.reduce((totalVal, currentVal) => {
    //     return totalVal + currentVal.images_count
    //   }, 0)
    // }
  },
  watch: {
  
    oldSeriesData: {
      handler: function (newVal) {

        if (newVal) {
          this.oldSeriesCount = this.oldSeriesData.filter(e => !e.isHidden).length
          this.oldImagesCount = this.oldSeriesData.filter(e => !e.isHidden).reduce((totalVal, currentVal) => {
            return totalVal + currentVal.images_count
          }, 0)
        }
      },
      deep: true,
      //vue 对于新加的属性监听不到
    },

    newSeriesDataList(newVal) {
      // console.log('序列数组发生变化',newVal);
      //序列数 、影像数变化
      if (newVal) {
        this.allSeriesCount = []
        this.allImageCount = []
        newVal.map(e => {
          this.allSeriesCount.push(e.length)
          this.allImageCount.push(e.reduce((totalVal, currentVal) => {
            return totalVal + currentVal.images_count
          }, 0))

        })
      }
    },
    // newInfoList(newVal) {
    //   if (newVal && newVal.length > 0) {
    //     //取消患者编号不同不能拆分限制
    //     this.splitDisabled = newVal.some(e => e.patient_id !== this.oldInfo.patient_id)
    //   }
    // }
    // oldCheckList(newVal) {
    //   console.log(newVal)
    // },
    // closeLoading(newVal) {
    //   if(newVal) {
    //     this.loading.close()
    //   }
    // }
  },
  methods: {
    //拆分主检查、检查编号存在多个
    mainCheckChanged(val) {
      console.log('选中的参数是啥？', val);
      this.selected_number_id = val
      let splitInfo = this.splitInfoDataCheckList.find(e=>e.id===val)
      Object.assign(this.oldInfo, splitInfo)
      this.getSeriesInfo(this.oldInfo.id, 'old')
    },
    // 36371客服需求 改造
    SplitClose(val) {
      this.splitImageShow = false

      if (val === true) {
        //拆分成功了
        this.toImgList()
      }
    },
    recoverSubcheckFn(index) {
      //恢复子检查中对应选中的影像
     let items = this.newCheckList[index]
     let newSeries = this.newSeriesDataList[index]

     if(items.length === 0)
     {
      //请选择需要恢复的序列
      this.$message({
          type: 'warning',
          message: '请选择要恢复的序列'
        })
        return
     }
     let newInfo = index < this.newInfoList.length ? this.newInfoList[index] : {}

    //  debugger
     items.map(e=>{
      
      this.oldSeriesData.map(oldE=>{
        if(oldE.id === e && oldE.isHidden && oldE.cutNumber === newInfo.accession_number)
        {
          oldE.isHidden = false
        }
      })
      let index = newSeries.findIndex(ele=>ele.id === e)
      if(index !== -1)
      {
        newSeries.splice(index,1)
      }
     })
     this.newCheckList[index] = []
     this.getOldoldSeriesDataCount()

    //  newSeries.map(e)
      // let newSeriesData = this.newSeriesDataList[index]
      // console.log('数据哦',this.newSeriesDataList,newSeriesData);
      // if(newSeriesData&&newSeriesData.length>0)
      //    {
      //     newSeriesData.map(e=>e.isHidden=false)
      //     this.getOldoldSeriesDataCount()
      //    }

    },
    recoverMainCheckFn(index) {
      let newSeriesData = this.newSeriesDataList[index]
      // console.log('数据哦', this.newSeriesDataList, newSeriesData);

      if (newSeriesData && newSeriesData.length > 0) {
        let newInfo = index < this.newInfoList.length ? this.newInfoList[index] : {}

        newSeriesData.map(e => {
          if(e.isHidden && e.cutNumber === newInfo.accession_number)
          {
            e.isHidden = false
          }
        })
        this.getOldoldSeriesDataCount()
      }
    },
    removeAllSubCheckFn() {
      //恢复所有被剪切的影像
      this.newSeriesDataList.map(e => e.map(e => e.isHidden = false))
      // //删除所有子检查
      this.allAccessionNumberModels.splice(0, this.allAccessionNumberModels.length)
      this.newStepNums.splice(0, this.newStepNums.length)
      this.newSeriesDataList.splice(0, this.newSeriesDataList.length)
      this.newCheckList.splice(0, this.newCheckList.length)

      this.newInfoList.splice(0, this.newInfoList.length)
      //默认添加新的子检查

      this.addAccession()

    },
    resetSubCheckFn(index) {
      //恢复从主检查中剪切过来的数据
      this.recoverMainCheckFn(index)
      //删除对应的子检查
      if (index < this.newSeriesDataList.length)
        this.newSeriesDataList.splice(index, 1, [])
      if (index < this.newCheckList.length)
        this.newCheckList.splice(index, 1, [])

      if (index < this.newInfoList.length) {
        this.newInfoList.splice(index, 1, [])
      }
    },
    removeSubcheckFn(index) {
      //恢复从主检查中剪切过来的数据
      this.recoverMainCheckFn(index)
      //删除对应的子检查
      if (index < this.allAccessionNumberModels.length) {
        this.allAccessionNumberModels.map((e, eIndex) => {
          if (eIndex > index) e.index--
          return e
        })
        // console.log('移除后的数据变更',this.allAccessionNumberModels);
        this.allAccessionNumberModels.splice(index, 1)
      }

      if (index < this.newStepNums.length)
        this.newStepNums.splice(index, 1)
      if (index < this.newSeriesDataList.length)
        this.newSeriesDataList.splice(index, 1)
      if (index < this.newCheckList.length)
         this.newCheckList.splice(index, 1)
      if (index < this.newInfoList.length) {
        this.newInfoList.splice(index, 1)
      }
      //删除患者信息之后，需要重新修改确定按钮状态
    },

    addAccession() {

      if (this.newStepNums.length > 0) {
        //默认新增一条检查记录
        this.newStepNums.splice(0, 0, '')//增加一条空的检查编号
        this.newInfoList.splice(0, 0, { patient_id: '', patient_name: '', patient_sex: '', patient_age: '', accession_number: '', modalities_in_study: '', study_date_time: '' })//新增一条数据信息
        //插入的话
        let arr = this.allAccessionNumberModels.map(e => {
          // console.log('数据不对哦，',e);
          e.index = e.index + 1
          return e
        })
        

        this.allAccessionNumberModels.splice(0, 0, { num: '', index: 0 })
        this.newSeriesDataList.splice(0, 0, [])
        this.newCheckList.splice(0,0,[])

        // console.log('插入数据变更', arr);
      } else {
        //默认新增一条检查记录
        this.newStepNums.push('')//增加一条空的检查编号
        this.newInfoList.push({ patient_id: '', patient_name: '', patient_sex: '', patient_age: '', accession_number: '', modalities_in_study: '', study_date_time: '' })//新增一条数据信息
        this.allAccessionNumberModels.push({ num: '', index: 0 })
        this.newSeriesDataList.push([])
        this.newCheckList.push([])
      }
      // console.log(this.allAccessionNumberModels,'添加模块');

    },
    getOldoldSeriesDataCount() {
      this.oldSeriesCount = this.oldSeriesData.filter(e => !e.isHidden).length
      this.oldImagesCount = this.oldSeriesData.filter(e => !e.isHidden).reduce((totalVal, currentVal) => {
        return totalVal + currentVal.images_count
      }, 0)
    },

    //此方法无用
    async getIMGList(accession_number) { // 获取列表
      let res = await this.$pacsApi.pacsApi.getIMGList(accession_number)
      const { code, data, page } = res
      if (code === 0 && data.length > 0) {
        Object.assign(this.oldInfo, data[0])
        this.getSeriesInfo(this.oldInfo.id, 'old')
      }
    },
    async getSplitInfo(accession_number) { // 获取检查信息（用于拆分）

      let res = await this.$pacsApi.pacsApi.getSplitInfo(accession_number)
      const { code, data, page } = res
      if (code === 0) {
        if (data instanceof Array && data.length > 0) {
          if(data.length>1){
            this.splitInfoDataCheckList = data.map((e, index) => ({ ...e, name: `检查${index+1}` }))
          }else{
            this.splitInfoDataCheckList = []
          }

          //默认展示第一个
          //默认显示选中 的若无则展示第一个  
          if (this.selected_number_id) {
            let getInfo = data.find(e => e.id === this.selected_number_id && e.accession_number === this.stepOneCheckNum)
            if (getInfo !== undefined) {
              Object.assign(this.oldInfo, getInfo)
            } else {
              Object.assign(this.oldInfo, data[0])
            }
            console.log('筛选出来的参数哦',getInfo,this.oldInfo,this.selected_number_id);
          } else {
            Object.assign(this.oldInfo, data[0])
          }
          this.selectedSplitInfo = this.oldInfo.id

          this.getSeriesInfo(this.oldInfo.id, 'old')
        }else{
          this.splitInfoDataCheckList = []
        }

      }
    },
    oldQueryFn() {

      if (this.oldInfo.accession_number !== this.stepOneCheckNum
        && this.newInfoList.some(e => e.patient_id)) {
        //主检查变化发生变化      

        this.$confirm('重新查询将不保存本次拆分结果', '请确认!', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          dangerouslyUseHTMLString: true,
        }).then((action) => {
          //清空所有子检查
          this.removeAllSubCheckFn()
          this.oldInfo = this.$options.data().oldInfo
          this.oldSeriesData = this.$options.data().oldSeriesData
          this.oldCheckList = this.$options.data().oldCheckList
          this.getSplitInfo(this.stepOneCheckNum)

        }).catch((action) => {
          this.stepOneCheckNum = this.oldInfo.accession_number
          this.$message({
            type: 'info',
            message: '已取消变更主检查号'
          });
        });
      } else {
        this.oldInfo = this.$options.data().oldInfo
        this.oldSeriesData = this.$options.data().oldSeriesData
        this.oldCheckList = this.$options.data().oldCheckList
        this.getSplitInfo(this.stepOneCheckNum)
      }

    },
    async getSeriesInfo(id, type) {
    
      let res = await this.$pacsApi.pacsApi.getSeriesInfo(id)
      let { code, data } = res
      if (code === 0) {
        if (data.length === 0) {
          // this[type + 'SeriesCount'] = 0
          // this[type + 'ImagesCount'] = 0
          this[type + 'SeriesData'] = []
        } else {
          // this[type + 'SeriesCount'] = data.length
          // this[type + 'ImagesCount'] = data.reduce((totalVal, currentVal) => {
          //   return totalVal + currentVal.images_count
          // }, 0)
          let readerPromise = (fileRes) => {
            return new Promise((resolve, reject) => {
              let reader = new FileReader()
              reader.readAsDataURL(fileRes)
              reader.onload = () => {
                // console.log(reader.result)
                resolve(reader.result)
              }
            })
          }
          let forFn = async () => {
            for (let i = 0; i < data.length; i++) {
              let fileRes = await this.$pacsApi.pacsApi.getSeriesImg(data[i]['id'])
              let readerResult = await readerPromise(fileRes)
              // console.log(readerResult)
              this.$set(data[i], 'imgSrc', readerResult)
            }
          }
          forFn()
          // data.forEach(async (ele, index) => {
          //   let fileRes = await this.$pacsApi.pacsApi.getSeriesImg(ele.id)
          //   let blobData = new Blob([fileRes])
          //   let imgUrl = URL.createObjectURL(blobData)
          //   this.$set(data[index], 'imgSrc', imgUrl)
          // })


          //重复查询且已拆分过的----对剪切的处理
          if (this.newSeriesDataList.length > 0) {
            let dataList = []
            this.newSeriesDataList.map(e => e.map(ele => { dataList.push(ele) }))
            let arr = dataList.filter(e => e.isHidden)
            let newArr = [...new Set(arr)]
            // console.log('剪切数据有误', newArr, dataList, data);
            newArr.map(e => {
              let item = data.find(ele => ele.id === e.id)
              // console.log('找得到吗？', item);
              if (item !== undefined) item.isHidden = true
            })
          }
          this[type + 'SeriesData'] = data
        }
      }
    },
    // 影像拆分信息
    async getSplittingInfo(index) {

      let accession_number = this.newStepNums[index]

      let res = await this.$pacsApi.pacsApi.getSplittingInfo({ accession_number })


      let { code, data } = res
      if (code === 0) {
        if (data) {

          // this.splitDisabled = false
          // if (data.patient_id !== this.oldInfo.patient_id) {
          //   this.$message.warning('查询到的RIS患者编号与存档显示的不一致，无法进行拆分')
          //   this.resetSubCheckFn(index)
          //   console.log('查询到的RIS患者编号与存档显示的不一致，无法进行拆分', data.patient_id, this.oldInfo.patient_id);

          //   // this.splitDisabled = true
          // }





          if (index < this.newInfoList.length) {
            this.newInfoList.splice(index, 1, data)
          } else {
            this.newInfoList.splice(0, 0, data)
          }



          let findItem = this.allAccessionNumberModels.find(e => e.num === accession_number)


          //检查编号变化？
          if (index < this.newSeriesDataList.length) {
            ////复原主检查剪切过的序列
            //  
            if (findItem !== undefined && findItem.index !== index) {
              //修改的检查编号一模一样
              this.recoverMainCheckFn(index)
              this.newSeriesDataList.splice(index, 1, [])
              this.newCheckList.splice(index, 1, [])
            }
          } else {
            this.newSeriesDataList.splice(0, 0, [])
            this.newCheckList.splice(0, 0, [])
            this.recoverMainCheckFn(index)
          }

          if (index < this.allAccessionNumberModels.length) {
            this.allAccessionNumberModels.splice(index, 1, { num: accession_number, index: index })
          } else {
            this.allAccessionNumberModels.splice(0, 0, { num: accession_number, index: index })
          }

          // console.log('没有添加成功？',this.allAccessionNumberModels);



        } else {
          this.$message.warning('未查询到记录，请重新输入')
          this.resetSubCheckFn(index)

          // this.splitDisabled = true
        }
      }
    },
    //对于已经存在的检查编号信息---如果修改失败直接恢复原检查编号
    newQueryAccessionNumber(index) {

      let model = this.allAccessionNumberModels.find(e => e.index === index)
      if (model === undefined) {
        this.newStepNums.splice(index, 1, '')

      } else {
        this.newStepNums.splice(index, 1, model.num)

      }
      // if (index === 0 && this.allAccessionNumberModels.length === this.newStepNums.length) {
      //   //新添加的数据
      //   this.newStepNums.splice(index, 1, '')
      // } else {
      //   if (index < this.allAccessionNumberModels.length - 1) {
      //     this.newStepNums.splice(index, 1, this.allAccessionNumberModels[index + 1])
      //   } else {
      //     this.newStepNums.splice(index, 1, '')
      //   }
      // }

    },
    newQueryFn(index) {

      if (index >= this.newStepNums.length) return
      let newNums = this.newStepNums[index]
      if (newNums === '') {
        this.$message({
          type: 'warning',
          message: '请输入将影像拆分到的检查编号'
        })
        return
      }
      if (newNums !== '' && this.stepOneCheckNum === newNums) {
        this.$message({
          type: 'warning',
          message: '目标检查不能一致'
        })
        this.newQueryAccessionNumber(index)
        return
      }
      let findItem = this.allAccessionNumberModels.find(e => e.num === newNums)
      // console.log('提示错误哦', findItem, index, this.allAccessionNumberModels, this.newStepNums);
      if (findItem !== undefined) {
        if (index !== findItem.index) {
          this.$message({
            type: 'warning',
            message: '已存在该子检查'
          })
          this.newQueryAccessionNumber(index)
          return

        }
      }

      // this.newInfo = this.$options.data().newInfo
      // this.newSeriesData = this.$options.data().newSeriesData
      // this.newCheckList = this.$options.data().newCheckList
      this.getSplittingInfo(index)
      this.isQuerySecond = true
    },
    seriesCopy(index) {
      // //打包时记得恢复
      // this.splitDisabled = false
debugger
      if (this.oldCheckList.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要复制的序列'
        })
        return
      }
      let newInfo = index < this.newInfoList.length ? this.newInfoList[index] : {}
      // console.log('数据呢？', newInfo.accession_number);
      if (newInfo.accession_number === undefined || !newInfo || newInfo.accession_number === '') {
        this.$message({
          type: 'warning',
          message: '没有将影像拆分到的检查编号信息'
        })
        return
      }
      let copyArr = this.oldSeriesData.filter((ele) => {
        if (this.oldCheckList.includes(ele.id)) {
          return ele
        }
      })
      let newSeriesData = index < this.newSeriesDataList.length ? this.newSeriesDataList[index] : []

      for (let i = 0; i < newSeriesData.length; i++) {
        if (this.oldCheckList.includes(newSeriesData[i]['id'])) {
          this.$message({
            type: 'warning',
            message: '序列编号：' + newSeriesData[i]['series_number'] + ' 已经复制，不得重复复制'
          })
          this.oldCheckList = []
          return
        }
      }
      this.oldCheckList = []
      newSeriesData.push(...copyArr)
      if (index < this.newSeriesDataList.length) {

        this.newSeriesDataList.splice(index, 1, newSeriesData)
      } else {
        this.newSeriesDataList.push(newSeriesData)
      }
    },
    seriesCut(index) { // 剪切
      if (this.oldCheckList.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要剪切的序列'
        })
        return
      }
      let newInfo = index < this.newInfoList.length ? this.newInfoList[index] : {}
      let newSeriesData = index < this.newSeriesDataList.length ? this.newSeriesDataList[index] : []

      if (this.oldSeriesData.length === 1) {
        this.$confirm('序列数仅剩1条, 是否剪切?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (newInfo.accession_number === undefined || !newInfo || newInfo.accession_number === '') {
            this.$message({
              type: 'warning',
              message: '没有将影像拆分到的检查编号信息'
            })
            return
          }
          let repeatedNum = [] // 重复的
          let repeatedId = [] // 重复的ID
          let noRepeatedId = [] // 不重复的ID



          for (let i = 0; i < newSeriesData.length; i++) {
            if (this.oldCheckList.includes(newSeriesData[i]['id'])) {
              repeatedNum.push(newSeriesData[i]['series_number'])
              repeatedId.push(newSeriesData[i]['id'])
            }
          }
          for (let k = 0; k < this.oldCheckList.length; k++) {
            if (!repeatedId.includes(this.oldCheckList[k])) {
              noRepeatedId.push(this.oldCheckList[k])
            }
          }
          if (repeatedNum.length > 0) {
            this.$message({
              type: 'warning',
              message: '序列编号：' + repeatedNum.join(',') + ' 已经存在，不得重复剪切'
            })
          }
          let cutArr = []
          for (let j = 0; j < this.oldSeriesData.length; j++) {
            if (noRepeatedId.includes(this.oldSeriesData[j]['id'])) {
              cutArr.push(this.oldSeriesData[j])
              //不删除 ---兼容后续恢复
              this.oldSeriesData[j].isHidden = true;
              this.oldSeriesData[j].cutNumber = newInfo.accession_number;

              // this.oldSeriesData.splice(j, 1) // 选中了就删掉
              // j--
              continue
            }
            if (repeatedId.includes(this.oldSeriesData[j]['id'])) {
              // this.oldSeriesData.splice(j, 1) // 选中了就删掉
              //不删除 ---兼容后续恢复
              this.oldSeriesData[j].isHidden = true;
              this.oldSeriesData[j].cutNumber = newInfo.accession_number;

              // j--
            }
          }
          this.oldCheckList = []
          newSeriesData.push(...cutArr)
          if (index < this.newSeriesDataList.length) {

            this.newSeriesDataList.splice(index, 1, newSeriesData)
          } else {
            this.newSeriesDataList.push(newSeriesData)
          }

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      } else {
        if (newInfo.accession_number === undefined || !newInfo || newInfo.accession_number === '') {
          this.$message({
            type: 'warning',
            message: '没有将影像拆分到的检查编号信息'
          })
          return
        }
        let repeatedNum = [] // 重复的
        let repeatedId = [] // 重复的ID
        let noRepeatedId = [] // 不重复的ID

        for (let i = 0; i < newSeriesData.length; i++) {
          if (this.oldCheckList.includes(newSeriesData[i]['id'])) {
            repeatedNum.push(newSeriesData[i]['series_number'])
            repeatedId.push(newSeriesData[i]['id'])
          }
        }
        for (let k = 0; k < this.oldCheckList.length; k++) {
          if (!repeatedId.includes(this.oldCheckList[k])) {
            noRepeatedId.push(this.oldCheckList[k])
          }
        }
        if (repeatedNum.length > 0) {
          this.$message({
            type: 'warning',
            message: '序列编号：' + repeatedNum.join(',') + ' 已经存在，不得重复剪切'
          })
        }
        let cutArr = []
        for (let j = 0; j < this.oldSeriesData.length; j++) {
          if (noRepeatedId.includes(this.oldSeriesData[j]['id'])) {
            cutArr.push(this.oldSeriesData[j])
            // this.oldSeriesData.splice(j, 1) // 选中了就删掉
            //不删除 ---兼容后续恢复
            this.oldSeriesData[j].isHidden = true;
            this.oldSeriesData[j].cutNumber = newInfo.accession_number;

            // j--
            continue
          }
          if (repeatedId.includes(this.oldSeriesData[j]['id'])) {
            // this.oldSeriesData.splice(j, 1) // 选中了就删掉
            //不删除 ---兼容后续恢复
            this.oldSeriesData[j].isHidden = true;
            this.oldSeriesData[j].cutNumber = newInfo.accession_number;

            // j--
          }
        }
        this.oldCheckList = []
        newSeriesData.push(...cutArr)
        if (index < this.newSeriesDataList.length) {

          this.newSeriesDataList.splice(index, 1, newSeriesData)
        } else {
          this.newSeriesDataList.push(newSeriesData)
        }
      }

      this.getOldoldSeriesDataCount()

    },
    splitFn() {


      if (this.oldInfo.id === '') {
        this.$message({
          type: 'warning',
          message: '没有待拆分的影像'
        })
        return
      }
      if (this.oldSeriesCount === 0) {
        this.$message({
          type: 'warning',
          message: '主检查至少保留1个序列'
        })
        return
      }
      if (this.newInfoList.length == 0) {
        this.$message({
          type: 'warning',
          message: '请添加将影像拆分到的子检查'
        })
        return
      }
      //有重复的检查编号
      if (this.newInfoList.some(e => e.accession_number === this.oldInfo.accession_number)) {
        this.$message({
          type: 'warning',
          message: '请删除重复检查编号信息'
        })
        return
      }
      //有空的检查编号信息
      if (this.newInfoList.some(e => e.accession_number === '' || e.accession_number === undefined)) {
        this.$message({
          type: 'warning',
          message: '请输入将影像拆分到的检查编号信息'
        })
        return
      }
      // if (this.newInfoList.some(e => e.patient_id !== this.oldInfo.patient_id)) {
      //   this.$message({
      //     type: 'warning',
      //     message: '不能拆分不同人的影像'
      //   })
      //   return
      // }

      let numbers = [];
      this.newSeriesDataList.map((e, index) => {
        if (e.length === 0 && this.newStepNums.length > index) {
          numbers.push(`【${this.newStepNums[index]}】`)
        }
      })

      if (numbers.length > 0) {
        this.$message({
          type: 'warning',
          message: `检查编号 ${numbers.join('')}无影像，请为其复制或剪切序列`
        })
        return
      }


      this.splitImageShow = true


      // this.imgSplit({ old_series, new_series, ...this.newInfo }, this.oldInfo.id)
    },

    //弹框处理
    imgSplit(data, id) {
      // 开始菊花
      this.loading = this.$loading({
        lock: true,
        text: '拆分中...',
        spinner: 'el-icon-loading',
      });
      this.$pacsApi.pacsApi.imgSplit(data, id).then(res => {
        let { code, msg } = res
        if (code === 0) {
          this.$message({
            type: 'success',
            message: msg
          })
          this.loading.close();
        } else {
          this.loading.close();
          this.$message.error(msg)
        }
      }, err => {
        this.loading.close();
      }).catch(error => {
        this.loading.close();
      })
    },
    toImgList() {
      // if(this.$route.query.systemid && this.$route.query.scope) {
      //   this.$router.push({path: this.basePath + '/IMGLIST', query: {scope: this.$route.query.scope, systemid: this.$route.query.systemid}})
      // }else {
      //   this.$router.push({ path: this.basePath + '/IMGLIST' })
      // }
      // if(this.group === 'doct' && this.$route.query.systemid && this.$route.query.scope) { // 医生角色
      //   this.$router.push({path: this.basePath + '/IMGLIST', query: {scope: this.$route.query.scope, systemid: this.$route.query.systemid}})
      // }else if(this.group === 'dept' && this.$route.query.systemid) { // 科室角色
      //   this.$router.push({path: this.basePath + '/IMGLIST', query: {systemid: this.$route.query.systemid}})
      // }else {
      //   this.$router.push({ path: this.basePath + '/IMGLIST' })
      // }
      this.$router.push({ path: this.basePath + '/IMGLIST', query: { group: this.group, systemid: this.$route.query.systemid } })
    },
  },
  filters: {
    ageFormatter: function (value) {
      const patientAgeTypeMapping = {
        'Y': '岁',
        'M': '月',
        'D': '日',
        'W': '周'
      }
      let patientAgeNum = ''
      let patientAgeType = ''
      if (value) {
        patientAgeNum = value.substring(0, value.length - 1)
        patientAgeType = value.substring(value.length - 1, value.length)
        return patientAgeNum + patientAgeTypeMapping[patientAgeType]
      } else {
        return ''
      }
    }
  },

  async mounted() {

    console.log('影像拆分获取到的参数', this.$route);
    //换成检查列表

    this.basePath = process.env.NODE_ENV === 'development' ? '' : '/paservice'
    this.apiUrl = configUrl.apiUrl
    // let oldAccessionNumber = this.$route.query.accessionNumber
    // let oldAccessionNumber2 = this.$route.query.accessionNumber2
    // if (oldAccessionNumber) { // 获取相关信息
    //   this.oldInfo.accession_number = oldAccessionNumber
    //   this.stepOneCheckNum = oldAccessionNumber
    //   await this.getSplitInfo(oldAccessionNumber)
    //   if (oldAccessionNumber2) {
    //     this.stepTwoCheckNum = oldAccessionNumber2
    //     await this.newQueryFn()
    //   }

    // }

  this.selected_number_id =  this.$route.query.number_id

    let oldAccessionNumber = ''
    let numbers = []
    if (this.$route.query.accession_numbers instanceof Array) {
      oldAccessionNumber = this.$route.query.accession_numbers.length > 0 ? this.$route.query.accession_numbers[0] : undefined;   //分离出来主检查号以及子检查号
      numbers = this.$route.query.accession_numbers
    } else if (this.$route.query.accession_numbers.indexOf(',') !== -1) {
      numbers = this.$route.query.accession_numbers.split(',')
      oldAccessionNumber = numbers.length > 0 ? numbers[0] : this.$route.query.accession_numbers
    } else {
      oldAccessionNumber = this.$route.query.accession_numbers
    }
    if (oldAccessionNumber) { // 获取相关信息
      this.oldInfo.accession_number = oldAccessionNumber
      this.stepOneCheckNum = oldAccessionNumber
      await this.getSplitInfo(oldAccessionNumber)

      if ((numbers instanceof Array) && numbers.length > 1) {
        numbers.filter((e, index) => index !== 0).map(async (e, index) => {
          this.newStepNums.push(e);
          this.allAccessionNumberModels.push({ num: e, index: index })
          this.newInfoList.push({})
          this.newSeriesDataList.push([])
          this.newCheckList.push([])
          await this.newQueryFn(index)
        })
        // this.stepTwoCheckNum = oldAccessionNumber2
      } else {
        this.addAccession()
      }

    }

    if (this.$route.query.institutionId) {
      this.fromList = false
      store.commit('permission/SET_DEPTINSTITUTIONID', this.$route.query.institutionId)
    }
  },
  components: {
    HeadTabSwitch,
    SplitImgVue
  }
}
</script>

<style lang="less" scoped>
/deep/.modeNavBar {
  .pl5 {
    font-size: 14px;
    color: #acacac;
  }
}

.processBox {
  position: relative;
}

/deep/ .splittingImg {
  .el-input--medium .el-input__inner {
  height: 40px;
}
}

.btnBox {
  float: right;
  margin-left: 30px;

  button {
    width: 80px;
    height: 40px;
    background-color: #fff;
    padding: 0;
  }

  .subButton {
    width: 100px;
    height: 40px;
    background-color: #67C23A;

  }
}

.stepTwoBtnBox {
  float: right;

  button {
    width: 100px;
    height: 40px;
    background-color: #fff;
    border: 1px solid #DCDFE6;
    padding: 0;
  }
}

.spiltBtnBox {
  button {
    width: 100px;
    height: 40px;
    padding: 0;
  }
}

.ml20i {
  margin-left: 20px !important;
}

.f38i {
  font-size: 38px !important;
}

.patient_info_index {
  padding-left: 36px;
  padding-top: 5px;
  padding-bottom: 5px;

}

.patient_info {
  width: 100%;
  // height: 120px;
  margin-top: 5px;
  margin-bottom: 5px;
  box-sizing: border-box;
  border: 1px dashed #999;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

.img_box {
  overflow-x: auto;
  display: flex;

  div {
    margin-right: 54px;
  }
}
.box_img_width{
  width: calc(100%-214px);
}

/deep/.el-checkbox__input {
  position: absolute;
  top: 188px;
  right: 0;
  /*opacity: 0;*/
}

/deep/.el-checkbox__inner {
  width: 20px;
  height: 20px;
}

/deep/.el-checkbox__input.is-checked .el-checkbox__inner::after {
  margin-left: 3px;
  transform: rotate(45deg) scale(2)
}

/deep/.el-checkbox__inner::after {
  /*去除动画效果*/
  -webkit-transition: none !important;
  -moz-transition: none !important;
  -o-transition: none !important;
  transition: none !important;
}

.imgLoadFail {
  width: 94px;
  height: 90px;
  background: url("../../assets/images/pacs/imgLoadFail.png") no-repeat;
  background-size: 100% 100%;
}

.noImg {
  width: 58px;
  height: 90px;
  background: url("../../assets/images/pacs/noImg.png") no-repeat;
  background-size: 100% 100%;
}

.subCheck {
  color: #0A70B0;
}
</style>
